package com.bvgol.examples.nio.niosocket;/**
 * @Classname NIOClient
 * @Description TODO
 * @Date 2021/6/21 10:51
 * @Created by GUOCHEN
 */

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @program: my-spring-completely
 * @description:
 * @author: GUOCHEN
 * @create: 2021/06/21 10:51
 */
public class NIOClient {

    public static void startClient() {
        try {
            SocketChannel socketChannel = SocketChannel.open();

            socketChannel.configureBlocking(false);

            InetSocketAddress inetSocketAddress = new InetSocketAddress(6666);
            if (!socketChannel.connect(inetSocketAddress)) {
                while (!socketChannel.finishConnect()) {
                    System.out.println("连接需要时间,客户端不会阻塞,可以做其它工作");
                }
            }

            //连接成功
            String str = "hello -----中文--"+socketChannel.hashCode();
            ByteBuffer wrap = ByteBuffer.wrap(str.getBytes());

            //发送数据 === buffer写入 channel

            socketChannel.write(wrap);
            //阻塞这里
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws IOException {
        NIOClient.startClient();
    }
}
